package com.basin.common.core.async.standard;

import cn.hutool.core.date.StopWatch;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Data
@Slf4j
public abstract class AbstractBaseTask<T> {
    public AbstractBaseTask() {
        this.open();
    }

    private String taskId = UUID.randomUUID().toString();

    private T result;

    private T defaultResult = null;

    private Exception e;

    private long costTimeMs; // -1代表超时

    private long limitTimeMs = 60000; // 默认一分钟

    public abstract T execute() throws Exception;

    public abstract void callback();

    public final void run() {
        try {
            // 耗时统计
            StopWatch sw = new StopWatch();
            sw.start(taskId);
            this.result = this.execute();
            sw.stop();
            this.setCostTimeMs(sw.getTotalTimeMillis());
            if (this.costTimeMs >= this.limitTimeMs) {
                throw new TimeoutException();
            }
        } catch (Exception e) {
            log.error("线程执行异常 {}", this.getTaskId(), e);
            this.e = e;
            this.result = this.defaultResult;
            this.costTimeMs = -1;
        }
    }

    public void open() {
    }
}
